﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZyGames.DZPocker.Model;
using ZyGames.Framework.Game.Cache;

namespace ZyGames.DZPocker.Bll.Logic
{
	public class GameFriendShip
	{
		private static GameFriendShip _instance;
		private GameDataCacheSet<FriendShip> friendShipCache;

		static GameFriendShip()
		{
			_instance = new GameFriendShip();
		}

		private GameFriendShip()
		{
			this.friendShipCache = new GameDataCacheSet<FriendShip>();
		}

		public static GameFriendShip Current
		{
			get { return _instance; }
		}

		public bool CreateFrindShip(int userid, int friendid)
		{
			FriendShip friendShip = new FriendShip(userid, friendid);
			var friendShips = this.friendShipCache.FindAll(userid.ToString());
			if (friendShips.Count > 0)
			{
				var friendShipModel = friendShips.FirstOrDefault(i => i.FriendID == friendid);
				if (friendShipModel != null)
				{
					Console.WriteLine(string.Format("添加好友关系失败，已经存在该记录: 我的ID:{0}, 好友ID:{1},  更新数据库", userid, friendid));
					return false;
				}
			}
			if (this.friendShipCache.Add(friendShip) && this.friendShipCache.Add(new FriendShip(friendid, userid)))
			{
				Console.WriteLine(string.Format("添加好友关系成功: 我的ID:{0}, 好友ID:{1},  更新数据库", userid, friendid));
				this.friendShipCache.Update();
				return true;
			}
			else
			{
				Console.WriteLine(string.Format("添加好友关系失败: 我的ID:{0}, 好友ID:{1},  更新数据库", userid, friendid));
				return false;
			}
		}

		public bool DeleteFriendShip(int userid, int friendid)
		{
			if (this.friendShipCache.Delete(new FriendShip(userid, friendid)) && this.friendShipCache.Delete(new FriendShip(friendid, userid)))
			{
				Console.WriteLine(string.Format("删除好友关系成功: 我的ID:{0}, 好友ID:{1},  更新数据库", userid, friendid));
				this.friendShipCache.Update();
			}
			else
			{
				Console.WriteLine(string.Format("删除好友关系出现问题: 我的ID:{0}, 好友ID:{1}", userid, friendid));
				return false;
			}
			return true;
		}

		/// <summary>
		/// 判断是否是好友
		/// </summary>
		/// <param name="userid"></param>
		/// <param name="friendid"></param>
		/// <returns></returns>
		public bool IsFriend(int userid, int friendid)
		{
			var allFriendShips = this.friendShipCache.FindAll(userid.ToString());
			if (allFriendShips.Count <= 0)
				return false;
			var friendShip = allFriendShips.FirstOrDefault(i => i.FriendID == friendid);
			if (friendShip == null)
				return false;
			else
				return true;
		}

		/// <summary>
		/// 获得某个玩家的所有好友ID
		/// </summary>
		/// <param name="userid"></param>
		/// <returns></returns>
		public List<int> GetFriendsId(int userid)
		{
			var friendShip = this.friendShipCache.FindAll(userid.ToString());
			var friendsId = new List<int>();
			foreach (var pair in friendShip)
			{
				if (pair.FriendID != userid)
					friendsId.Add(pair.FriendID);
			}
			return friendsId;
		}
	}
}
